import request from "@/request";
import { ref } from "vue";
import { z } from "zod"

const useAjax = <T extends z.ZodType<any, any>, ParamType>(config: {
  api: string,
  schema: T
}) => {

  const { api, schema } = config;

  const loading = ref(false);

  const data = ref<z.infer<T>>(schema.parse({}));

  const doAjax = async (param?: ParamType) => {
    loading.value = true;
    const result = await request.post(api, param);

    try {
      data.value = schema.parse(result)
    } catch (error) {
      console.log(api,error);
      
      // 后端数据不符合规范
    }

    console.log(api,result,data.value);
      
    loading.value = false;

    return data.value;
  }

  return {
    data,
    loading,
    doAjax,
  }
}
export default useAjax;